﻿using AspNetCoreRateLimit;
using Autofac.Core;
using Microsoft.Extensions.DependencyInjection;
using MyCompany.MyProject.Common;
using MyCompany.MyProject.Common.Caches;
using MyCompany.MyProject.Common.Core;
using MyCompany.MyProject.Common.Option;
using MyCompany.MyProject.Extensions.Redis;
using StackExchange.Redis;

#nullable disable

namespace MyCompany.MyProject.Extensions.ServiceExtensions
{
    public static class CacheSetup
    {
        /// <summary>
        /// 统一注册缓存
        /// </summary>
        /// <param name="services"></param>
        public static void AddCacheSetup(this IServiceCollection services)
        {
            var cacheOptions = App.GetOptions<RedisOption>();
            if (cacheOptions.Enable)
            {
                services.AddSingleton<IConnectionMultiplexer>(sp =>
                {
                    //获取连接字符串
                    var configuration = ConfigurationOptions.Parse(cacheOptions.ConnectionString, true);
                    configuration.ResolveDns = true;
                    return ConnectionMultiplexer.Connect(configuration);
                });
                services.AddSingleton<ConnectionMultiplexer>(p => p.GetService<IConnectionMultiplexer>() as ConnectionMultiplexer);

                //使用Redis
                services.AddStackExchangeRedisCache(options =>
                {
                    options.ConnectionMultiplexerFactory = () => Task.FromResult(App.GetService<IConnectionMultiplexer>(false));
                    if (!string.IsNullOrEmpty(cacheOptions.InstanceName)) options.InstanceName = cacheOptions.InstanceName;
                });

                // 使用 Redis 存储 IP 限流
                services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
                services.AddSingleton<IProcessingStrategy, AsyncKeyLockProcessingStrategy>();
                services.AddSingleton<IIpPolicyStore, DistributedCacheIpPolicyStore>();
                services.AddSingleton<IRateLimitCounterStore, DistributedCacheRateLimitCounterStore>();

                services.AddTransient<IRedisBasketRepository, RedisBasketRepository>();
            }
            else
            {
                //使用内存
                services.AddMemoryCache();
                services.AddDistributedMemoryCache();
                // 添加速率限制服务
                services.AddInMemoryRateLimiting();
            }

            services.AddSingleton<ICaching, Caching>();
            // 添加配置解析器
            services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
        }
    }
}
